<template>
	<div>
		<el-dialog :title="title" :visible.sync="isShow" :close-on-click-modal="false" :before-close="close" width="1000px">
			<div class="form-box">
				<el-form ref="form" :model="form" :rules="rules" label-width="90px">
					<el-row>
						<el-col :span="12">
							<el-form-item label="上传Logo" prop="shopLogo">
								<el-upload
									ref="upload1"
									:class="{'upload-cover-disabled': form.shopLogo}"
									list-type="picture-card"
									:file-list="fileList1"
									:limit="1"
									:accept="'image/*'"
									action=""
									:http-request="(file) => getQiniuToken(file, 1)"
									:on-remove="() => handleRemove(1)"
								>
									<i class="el-icon-plus avatar-uploader-icon" slot="default" ></i>
								</el-upload>
								
								<el-alert class="upload-progress" type="warning" title="" v-if="isUploading1">
									<template slot="title">
										<div class="upload-progress-text">
											<i class="el-icon-loading"></i>
											<span>上传中，请勿关闭窗口!</span>
										</div>
									</template>
								</el-alert>
								<el-alert class="upload-progress" type="success" title="上传成功!" show-icon v-if="isUploadingSuccess1"></el-alert>
							</el-form-item>
						</el-col>
						
						<el-col :span="12">
							<el-form-item label="上传海报" prop="posterUrl">
								<el-upload
									ref="upload2"
									:class="{'upload-cover-disabled': form.posterUrl}"
									list-type="picture-card"
									:file-list="fileList2"
									:limit="1"
									:accept="'image/*'"
									action=""
									:http-request="(file) => getQiniuToken(file, 2)"
									:on-remove="() => handleRemove(2)"
								>
									<i class="el-icon-plus avatar-uploader-icon" slot="default" ></i>
								</el-upload>
								
								<el-alert class="upload-progress" type="warning" title="" v-if="isUploading2">
									<template slot="title">
										<div class="upload-progress-text">
											<i class="el-icon-loading"></i>
											<span>上传中，请勿关闭窗口!</span>
										</div>
									</template>
								</el-alert>
								<el-alert class="upload-progress" type="success" title="上传成功!" show-icon v-if="isUploadingSuccess2"></el-alert>
							</el-form-item>
						</el-col>
					</el-row>
					
					<el-row>
						<el-col :span="24">
							<el-form-item label="店铺名称" prop="shopName">
								<el-input v-model="form.shopName" placeholder="请填写店铺名称" clearable></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					
					<el-row>
						<el-col :span="12">
							<el-form-item label="店铺编号" prop="shopNo">
								<el-input v-model="form.shopNo" placeholder="请填写店铺编号" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="所属社区" prop="departmentId">
								<el-select v-model="form.departmentId" placeholder="请选择所属社区" style="width: 100%;">
									<el-option v-for="item of departmentList" :key="item.id" :value="item.id" :label="item.departmentName"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					
					<el-row>
						<el-col :span="12">
							<el-form-item label="联系电话" prop="phone">
								<el-input v-model="form.phone" placeholder="请填写联系电话" clearable></el-input>
							</el-form-item>
						</el-col>
						
						<el-col :span="12">
							<el-form-item label="营业时间" prop="businessBeginTime">
								<div style="display: flex;">
									<el-time-picker v-model="form.businessBeginTime" format="HH:mm:ss" value-format="HH:mm:ss" :default-value="new Date(0,0,0,8,0,0)" placeholder="开始时间"></el-time-picker>
									<span style="margin: 0 12px;">至</span>
									<el-time-picker v-model="form.businessEndTime" format="HH:mm:ss" value-format="HH:mm:ss" :default-value="new Date(0,0,0,22,0,0)" placeholder="结束时间"></el-time-picker>
								</div>
							</el-form-item>
						</el-col>
					</el-row>
					
					<el-row>
						<el-col :span="24">
							<el-form-item label="店铺地址" prop="shopAddress">
								<el-input v-model="form.shopAddress" placeholder="请填写店铺地址" clearable></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					
					<el-row>
						<el-col :span="9">
							<el-form-item label="经度" prop="">
								<el-input v-model="form.lng" placeholder="填写经度或者在地图上选择" clearable></el-input>
							</el-form-item>
						</el-col>
						
						<el-col :span="8">
							<el-form-item label="纬度" prop="" label-width="50px">
								<el-input v-model="form.lat" placeholder="写纬度或者在地图上选择" clearable></el-input>
							</el-form-item>
						</el-col>
						
						<el-col :span="6">
							<el-form-item label-width="30px">
								<el-button @click="openMap">在地图上选择</el-button>
							</el-form-item>
							
						</el-col>
					</el-row>
					
					<el-row>
						<el-col :span="12">
							<el-form-item label="打包费(元)" prop="balingCharges">
								<el-input v-model="form.balingCharges" placeholder="请填写店铺打包费用" clearable></el-input>
							</el-form-item>
						</el-col>
						
						<el-col :span="12">
							<el-form-item label="是否可以提货" prop="shopPickupStatus" label-width="120px">
								<el-radio-group v-model="form.shopPickupStatus">
									<el-radio :label="1">是</el-radio>
									<el-radio :label="0">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
					</el-row>
					
					<el-row>
						<el-col :span="12">
							<el-form-item label="店铺装修皮肤" prop="businessType" label-width="120px">
								<el-radio-group v-model="form.businessType">
									<el-radio :label="0">默认皮肤</el-radio>
									<el-radio :label="1">指定皮肤</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
					</el-row>
					
					<el-row>
						<el-col :span="24">
							<el-form-item label="店铺说明" prop="remark">
								<el-input type="textarea" v-model="form.remark" :rows="5" placeholder="请填写店铺说明或者介绍" clearable></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					
					<el-row v-if="isEdit">
						<el-col :span="24">
							<el-form-item label="营业状态" prop="businessStatus">
								<el-radio-group v-model="form.businessStatus">
									<el-radio :label="1">营业中</el-radio>
									<el-radio :label="2">停止营业</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</div>
			
			<div slot="footer">
				<el-button type="primary" @click="submit">保 存</el-button>
				<el-button @click="reset" v-if="!isEdit">重 置</el-button>
				<el-button @click="close">取 消</el-button>
			</div>
		</el-dialog>
		
		<el-dialog title="点击地图，直接选择地点" :visible.sync="isShowMap" :close-on-click-modal="false" :before-close="closeMap" width="1200px">
			<div id="map" style="height: 800px;"></div>
			
			<div slot="footer">
				<el-button @click="closeMap">完 成</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import dayjs from 'dayjs'
	import TMap from '@/libs/map'
	import * as qiniu from 'qiniu-js'
	import { getQiniuToken } from '@api/common/common'
	import { getShopDetail, addShop, editShop } from '@api/shop/shop'
	import { AllDepartmentList } from '@api/department/department'
	export default {
		props: {
			isShow: Boolean,
			id: Number,
			isEdit: Boolean,
		},
		data() {
			let validateLogo = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请上传店铺logo图片'));
				} else {
					callback();
				}
			}
			let validateBusinessTime = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请选择店铺开始营业时间'));
				} else if(this.form.businessEndTime == '') {
					callback(new Error('请选择店铺结束营业时间'));
				} else {
					callback();
				}
			}
			return {
				form: {
					shopNo: '',
					shopName: '',
					departmentId: '',
					shopLogo: '',
					posterUrl: '',
					phone: '',
					shopAddress: '',
					businessBeginTime: '',
					businessEndTime: '',
					shopPickupStatus: 0,
					balingCharges: '',
					businessType: 0,
					remark: '',
					businessStatus: '',
					lng: '',
					lat: '',
				},
				rules: {
					shopLogo: [{required: true, validator: validateLogo, trigger: 'blur'}],
					shopNo: [{ required: true, message: '请填写店铺编号', trigger: 'blur' }],
					shopName: [{ required: true, message: '请填写店铺名称', trigger: 'blur' }],
					departmentId: [{ required: true, message: '请选择所属社区', trigger: 'blur' }],
					phone: [{ required: true, message: '请填写联系电话', trigger: 'blur' }],
					shopAddress: [{ required: true, message: '请填写店铺地址', trigger: 'blur' }],
					businessBeginTime: [{ required: true, validator: validateBusinessTime, trigger: 'blur' }],
					balingCharges: [{ required: true, message: '请填写店铺打包费用', trigger: 'blur' }],
				},
				
				departmentList: [],
				
				fileList1: [],
				isUploading1: false,
				isUploadingSuccess1: false,
				fileList2: [],
				isUploading2: false,
				isUploadingSuccess2: false,
				
				qiniuKey: '',
				qiniuToken: '',
				qiniuPutExtra: {},
				qiniuConfig: {
					useCdnDomain: true,
					retryCount: 6,
				},
				
				isShowMap: false,
				tMap: null, //地图实例
				TXMap: null, //地图原型
				markerLayer: null, //地图打点
			}
		},
		computed: {
			title() {
				let title = '店铺';
				if(this.isEdit) {
					title = '编辑' + title;
				} else {
					title = '添加' + title;
				}
				return title;
			}
		},
		watch: {
			isShow(val) {
				if(val) {
					if(this.isEdit) {
						this.getDetail();
					}
					this.getDepartment();
				}
			},
			'form.shopLogo': {
				handler(val) {
					if(val) {
						this.$refs['form'].clearValidate('shopLogo');
					}
				},
				deep: true
			},
		},
		methods: {
			getDetail() {
				getShopDetail({shopId: this.id})
					.then(res => {
						this.form.shopNo = res.data.shopNo;
						this.form.shopName = res.data.shopName;
						this.form.departmentId = res.data.departmentId ? res.data.departmentId : '';
						this.form.shopLogo = res.data.shopLogo;
						this.form.posterUrl = res.data.posterUrl;
						this.form.phone = res.data.phone;
						this.form.shopAddress = res.data.shopAddress;
						this.form.lng = res.data.lng;
						this.form.lat = res.data.lat;
						this.form.businessBeginTime = res.data.businessBeginTime;
						this.form.businessEndTime = res.data.businessEndTime;
						this.form.balingCharges = res.data.balingCharges;
						this.form.remark = res.data.remark;
						this.form.shopPickupStatus = res.data.shopPickupStatus;
						this.form.businessStatus = res.data.businessStatus;
						this.form.businessType = res.data.businessType;
						
						if(this.form.shopLogo) {
							this.fileList1.push({
								name: 'shopLogo',
								url: this.form.shopLogo
							});
						}
						if(this.form.posterUrl) {
							this.fileList2.push({
								name: 'posterUrl',
								url: this.form.posterUrl
							});
						}
						
					})
			},
			getDepartment() { //获取部门信息
				AllDepartmentList()
					.then(res => {
						this.departmentList = res.data;
					})
			},
			
			openMap() { //打开地图弹窗
				this.isShowMap = true;
				
				this.$nextTick(() => {
					this.initMap();
					
					setTimeout(() => {
						let _txMap = this.TXMap;
						let _tMap = this.tMap;
						if(this.isEdit && this.form.lat) {
							_tMap.setCenter(new _txMap.LatLng(this.form.lat, this.form.lng));
							
							this.markerLayer.updateGeometries([{
								id: 'mark',
								style: 'markerStyle',
								position: new _txMap.LatLng(this.form.lat, this.form.lng)
							}]);
						} else {
							_tMap.setCenter(new _txMap.LatLng(22.81356, 108.37036));
						}
					}, 500);
				});
			},
			closeMap() {
				this.isShowMap = false;
			},
			initMap() { //初始化地图
				if (this.tMap) {
					return;
				}
				
				let _self = this;
				TMap.init()
					.then(Map => {
						_self.TXMap = Map;
						let div = document.getElementById('map');
						
						_self.tMap = new Map.Map(div, {
							zoom: 18,
							viewMode: '2D',
							center: new Map.LatLng(22.81356, 108.37036)
						});
						_self.markerLayer = new Map.MultiMarker({
							map: _self.tMap,
							styles: {
								markStyle: new Map.MarkerStyle({
									width: 20,
									height: 30,
									anchor: {
										x: 10,
										y: 30
									}
								})
							},
							geometries: [{
								id: 'mark',
								style: 'markerStyle',
								position: new Map.LatLng(22.81356, 108.37036)
							}]
						});
						
						let _markerLayer = _self.markerLayer;
						_self.tMap.on('click', function(e) {
							let lat = e.latLng.lat.toFixed(5);
							let lng = e.latLng.lng.toFixed(5);
							_self.form.lat = lat;
							_self.form.lng = lng;
							_markerLayer.updateGeometries([{
								id: 'mark',
								style: 'markerStyle',
								position: new Map.LatLng(lat, lng)
							}])
						});
				
					});
			},
			
			//七牛云上传图片
			getQiniuToken(file, type) {
				if(type == 1) {
					this.isUploading1 = true;
					this.isUploadingSuccess1 = false;
				} else {
					this.isUploading2 = true;
					this.isUploadingSuccess2 = false;
				}
				
				// console.log(file.file.name)
				let name = file.file.name.split('.');
				let subffixName = '.' + name[name.length-1];
				
				getQiniuToken({subffixName: subffixName})
					.then(res => {
						this.qiniuToken = res.data.token;
						this.qiniuKey = res.data.key;
						this.uploadFile(file, type);
					})
			},
			uploadFile(file, type) {
				//qiniu.upload(file, key, token, putExtra, config)
				const observable = qiniu.upload(
					file.file,
					this.qiniuKey,
					this.qiniuToken,
					this.qiniuPutExtra,
					this.qiniuConfig
				)
				
				// 上传开始
				observable.subscribe({
					next: res => {
						console.log(res)
					},
					error: err => {
						console.log(err)
						this.handleError(err, file, type)
					},
					complete: res => {
						console.log(res)
						this.handleSuccess(res, file, type)
					},
				});
			},
			
			handleSuccess (response, file, type) {
				// console.log('response:', response)
				this.$message.success('上传成功');
				
				if(type == 1) {
					this.fileList1.push(process.env.VUE_APP_OSS_DOMAIN + response.key);
					this.form.shopLogo = process.env.VUE_APP_OSS_DOMAIN + response.key;
					this.isUploadingSuccess1 = true;
				} else {
					this.fileList2.push(process.env.VUE_APP_OSS_DOMAIN + response.key);
					this.form.posterUrl = process.env.VUE_APP_OSS_DOMAIN + response.key;
					this.isUploadingSuccess2 = true;
				}
				
				this.isUploading1 = false;
				this.isUploading2 = false;
			},
			handleError (err, file, type) {
				console.log(err)
				this.$message.error('上传失败，请重新上传!');
				if(type == 1) {
					this.fileList1.splice(0);
				} else {
					this.fileList2.splice(0);
				}
				
				this.isUploading1 = false;
				this.isUploading2 = false;
			},
			handleRemove(type) {
				if(type == 1) {
					this.form.shopLogo = '';
					this.$refs.upload1.clearFiles();
					this.isUploading1 = false;
					this.isUploadingSuccess1 = false;
				} else {
					this.form.posterUrl = '';
					this.$refs.upload2.clearFiles();
					this.isUploading2 = false;
					this.isUploadingSuccess2 = false;
				}
			},
			
			submit() { //提交添加or编辑
				this.$refs.form.validate(valid => {
					if (valid) {
						let params = {
							shopNo: this.form.shopNo,
							shopName: this.form.shopName,
							departmentId: this.form.departmentId,
							shopLogo: this.form.shopLogo,
							posterUrl: this.form.posterUrl,
							phone: this.form.phone,
							shopAddress: this.form.shopAddress,
							lng: this.form.lng,
							lat: this.form.lat,
							businessBeginTime: this.form.businessBeginTime,
							businessEndTime: this.form.businessEndTime,
							shopPickupStatus: this.form.shopPickupStatus,
							businessType: this.form.businessType,
							balingCharges: this.form.balingCharges,
							remark: this.form.remark,
						}
						if(this.isEdit) {
							params.id = this.id;
							params.businessStatus = this.form.businessStatus;
							
							editShop(params)
								.then(() => {
									this.$message.success('店铺修改成功！');
									this.close();
									
									this.$emit('submit');
								})
						} else {
							addShop(params)
								.then(() => {
									this.$message.success('店铺添加成功！');
									this.close();
									
									this.$emit('submit');
								})
						}
					}
				})
			},
			reset() {
				this.form.shopNo = '';
				this.form.shopName = '';
				this.form.departmentId = '';
				this.form.phone = '';
				this.form.shopAddress = '';
				this.form.lng = '';
				this.form.lat = '';
				this.form.businessBeginTime = '';
				this.form.businessEndTime = '';
				this.form.balingCharges = '';
				this.form.shopLogo = '';
				this.form.posterUrl = '';
				this.form.remark = '';
				this.form.businessStatus = '';
				this.form.businessType = 0;
				this.form.shopPickupStatus = 0;
				
				this.$refs.upload1.clearFiles();
				this.$refs.upload2.clearFiles();
				this.fileList1 = [];
				this.fileList2 = [];
				this.isUploading1 = false;
				this.isUploading2 = false;
				this.isUploadingSuccess1 = false;
				this.isUploadingSuccess2 = false;
			},
			
			close() {
				this.$emit('close');
				this.reset();
			},
		}
	}
</script>

<style lang="scss" scoped>
	.form-box {
		padding: 20px 30px;
	}
	.el-alert {
		line-height: normal;
	}
	
	.upload {
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, .5);
		position: relative;
	}
	.upload-cover-disabled {
		::v-deep .el-upload {
			display: none;
		}
	}
</style>